import 'package:just_audio/just_audio.dart';
import '../models/music_model.dart';

class AudioPlayerService {
  static final AudioPlayerService _instance = AudioPlayerService._internal();
  factory AudioPlayerService() => _instance;
  AudioPlayerService._internal();

  final AudioPlayer _player = AudioPlayer();
  MusicModel? _currentMusic;

  AudioPlayer get player => _player;
  MusicModel? get currentMusic => _currentMusic;

  // 播放音乐
  Future<void> playMusic(MusicModel music) async {
    try {
      _currentMusic = music;
      
      // 如果音乐有直接的播放链接
      if (music.url.isNotEmpty) {
        await _player.setUrl(music.url);
        await _player.play();
      } else {
        // 如果没有直接链接，可以尝试从源链接获取
        print('没有可播放的音乐链接: ${music.title}');
      }
    } catch (e) {
      print('播放音乐失败: $e');
      rethrow;
    }
  }

  // 暂停播放
  Future<void> pause() async {
    await _player.pause();
  }

  // 继续播放
  Future<void> resume() async {
    await _player.play();
  }

  // 停止播放
  Future<void> stop() async {
    await _player.stop();
    _currentMusic = null;
  }

  // 跳转到指定位置
  Future<void> seek(Duration position) async {
    await _player.seek(position);
  }

  // 设置音量
  Future<void> setVolume(double volume) async {
    await _player.setVolume(volume);
  }

  // 获取播放状态流
  Stream<PlayerState> get playerStateStream => _player.playerStateStream;

  // 获取位置流
  Stream<Duration> get positionStream => _player.positionStream;

  // 获取时长流
  Stream<Duration?> get durationStream => _player.durationStream;

  // 获取当前播放状态
  bool get isPlaying => _player.playing;

  // 获取当前位置
  Duration get position => _player.position;

  // 获取总时长
  Duration? get duration => _player.duration;

  // 释放资源
  void dispose() {
    _player.dispose();
  }
}